package com.woniu.service.impl;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniu.OrderFeignClient;
import com.woniu.Result;
import com.woniu.UserFeignClient;
import com.woniu.dto.ComplainDto;
import com.woniu.dto.HandleComplainDto;
import com.woniu.pojo.Complaint;
import com.woniu.mapper.ComplaintMapper;
import com.woniu.pojo.Message;
import com.woniu.pojo.User;
import com.woniu.service.IComplaintService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yellow Docker
 * @since 2022-11-16
 */
@Service
@Slf4j
public class ComplaintServiceImpl extends ServiceImpl<ComplaintMapper, Complaint> implements IComplaintService {

    @Autowired
    private ComplaintMapper complaintMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static final String key = "complain:Shop:" ;

    /**
     * 提交订单
     * @param dto
     * @return
     */
    @Override
    public boolean submitComplainByDto(ComplainDto dto) {
        LambdaQueryWrapper<Complaint> wrapper =
                Wrappers.lambdaQuery(Complaint.class).eq(Complaint::getOrderId, dto.getOrderId());
        List<Complaint> complaints = this.list(wrapper);
        if(ObjectUtils.isNotEmpty(complaints)){
            return false;
        }
        Complaint complaint = new Complaint();
        complaint.setUserId(dto.getUserId());
        complaint.setComDate(new Date());
        complaint.setType(0);
        complaint.setStatus(0);
        complaint.setComContnet(dto.getComContnet());
        complaint.setOrderId(dto.getOrderId());
        boolean update = this.save(complaint);
        return update;
    }

    @Override
    public List<Complaint> queryShopComplain(Integer shopId) {
        return complaintMapper.selectShopComplain(shopId);
    }

    @Override
    public List<Complaint> queryUserComplain(Integer userId) {
        LambdaQueryWrapper<Complaint> co = Wrappers.lambdaQuery(Complaint.class).eq(Complaint::getUserId, userId);
        List<Complaint> complaintList = complaintMapper.selectList(co);
        return complaintList;
    }


    /**
     * 处理门店投诉
     * 1.判断投诉状态是否处理中，是则返回已处理，等待客户反馈，不是则可以处理
     * 2.查询redis中的shop+complain+id是否为空，空的话则创造，不空就加一
     * @return
     */
    @Override
    public Result handleShopComplain(HandleComplainDto dto) {
        Complaint complain = this.getById(dto.getComplainId());
        Integer shopId = orderFeignClient.getShopId(complain.getOrderId()).getData();
        String keys = key + dto.getComplainId();
        if(ObjectUtils.isEmpty(complain)){
            return Result.fail("该投诉不存在");
        }
        if(complain.getStatus()==1){
            return Result.fail("该投诉正在处理,请等待客户反馈");
        }
        if(complain.getStatus()==2){
            return Result.fail("该投诉已经处理");
        }
        if(complain.getStatus()==0){
            String resultStr = redisTemplate.opsForValue().get(keys);
            if(StringUtils.isEmpty(resultStr)){
                redisTemplate.opsForValue().set(keys,"1");
            }else{
                int result = Integer.parseInt(resultStr);
                redisTemplate.opsForValue().set(keys, String.valueOf((result+1)));
            }
            LambdaUpdateWrapper<Complaint> wrapper =
                    Wrappers.lambdaUpdate(Complaint.class).eq(Complaint::getId, dto.getComplainId())
                            .set(Complaint::getStatus, 1).set(Complaint::getHandleContent,dto.getHandleContnet())
                    .set(Complaint::getHandleDate,new Date()).set(Complaint::getShopId,shopId);
            boolean flag = this.update(wrapper);
            if(flag){
                User user = userFeignClient.getById(complain.getUserId()).getData();
                log.info(user.getTel() + ":" + "您的投诉编号为" + dto.getComplainId() + "已经处理");
//                SendSmsUtil.sendSms(user.getTel(),"您的" + id + "投诉已经处理");
                return Result.ok();
            }
        }
        return Result.fail();
    }

    /**
     * 拒绝投诉处理
     * @param id
     * @return
     */
    @Override
    public boolean rejectComplain(Integer id) {
        String keys = key + id;
        String resultStr = redisTemplate.opsForValue().get(keys);
        Complaint complaint = this.getById(id);
        int result = Integer.parseInt(resultStr);
        LambdaUpdateWrapper<Complaint> set = Wrappers.lambdaUpdate(Complaint.class);
        if(result>=3){
            set.eq(Complaint::getId, id).set(Complaint::getType, 1);
            boolean update = this.update(set);
            if(update){
                Message message = new Message();
                message.setType(1);
                message.setContent("多次沟通，由后台协调");
                message.setStatus(0);
                message.setUserId(complaint.getUserId());
                message.setShopId(0);
                rabbitTemplate.convertAndSend("complain-fanout","",message);
            }
        }else{
            set.eq(Complaint::getId, id).set(Complaint::getStatus, 0);
            this.update(set);
            Message message = new Message();
            message.setType(1);
            message.setContent("客户不满意处理结果，请尽快处理");
            message.setStatus(0);
            message.setUserId(complaint.getUserId());
            message.setShopId(complaint.getShopId());
            rabbitTemplate.convertAndSend("complain-message-exchange","message",message);
        }
        return true;
    }

    /**
     * 接受处理
     * @param id
     * @return
     */
    @Override
    public boolean acceptComplain(Integer id) {
        Complaint complain = this.getById(id);
        Integer shopId = orderFeignClient.getShopId(complain.getOrderId()).getData();
        LambdaUpdateWrapper<Complaint> set =
                Wrappers.lambdaUpdate(Complaint.class).eq(Complaint::getId, id).set(Complaint::getStatus, 2);
        boolean result = this.update(set);
        return result;
    }
}
